package com.luntan.school.web.servlet.util;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

@WebServlet(name = "BaseServlet", value = "/BaseServlet")
public class BaseServlet extends HttpServlet {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //保存请求和响应对象，在子类中使用
        this.request = request;
        this.response = response;

        //解决post乱码问题
        request.setCharacterEncoding("utf-8");

        //获取用户名请求的方法名
        String methodName = request.getParameter("method");

        try {
            /**
             * 利用Java反射机制，实现根据方法名动态获取到对应方法，并执行方法调用
             */
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,null);
        }catch (NoSuchMethodException e) {
            e.printStackTrace();
        }catch (InvocationTargetException e) {
            e.printStackTrace();
        }catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
